import { ref } from 'vue';
import { sortCards } from '@/utils/cardUtils';
import {generateUniqueId}from '@/utils/common';

export function useGameState() {
  const Room = ref(null);
  const selectedCard = ref([]);
  const upCard = ref([]);
  const pais = ref([]);
  const leftContainer = ref([]);
  const rightContainer = ref([]);
  const landlordCards = ref([]);
  
  
  // 处理玩家手牌初始化
  const initPlayerHand = (playerHand, playerName) => {
    return sortCards(playerHand.map((card, index) => ({
      ...card,
      uniqueId: generateUniqueId(card, playerName, index)
    })));
  };
  
  // 合并手牌和地主牌
  const mergeWithLandlordCards = (playerCards) => {
    return sortCards([
      ...playerCards.map(card => ({
        ...card,
        uniqueId: card.uniqueId || generateUniqueId(card, 'player')
      })),
      ...landlordCards.value.map((card, index) => ({
        ...card,
        uniqueId: generateUniqueId(card, 'landlord', index)
      }))
    ]);
  };
  
  // 处理广播消息
  const processBroadcast = (data, currentSx) => {
    const calculateNeighbors = (current) => ({
      left: current === 1 ? 3 : current - 1,
      right: current === 3 ? 1 : current + 1
    });
    
    const { left, right } = calculateNeighbors(currentSx);
    
    if (data.sx === left) {
      leftContainer.value = data.handCards;
    } else if (data.sx === right) {
      rightContainer.value = data.handCards;
    } else {
      console.warn('Invalid broadcaster position');
    }
  };
  
  return {
    Room,
    selectedCard,
    upCard,
    pais,
    leftContainer,
    rightContainer,
    landlordCards,
    initPlayerHand,
    mergeWithLandlordCards,
    processBroadcast
  };
}